<?php

namespace App\Library;

class Utils
{
    /**
     * @return static
     */
    public static function init(): static
    {
        return new static;
    }

    /**
     * @param array $list
     * @param string $pk
     * @param string $pid
     * @param string $child
     * @param int $root
     * @return array
     */
    public function listToTree(array $list, string $pk = 'id', string $pid = 'parentId', string $child = 'children', int $root = 0): array
    {
        if (!empty($list)) {
            $arr = [];
            foreach ($list as $sorData) {
                if ((int)$sorData[$pid] === $root) {
                    $sorData[$child] = $this->listToTree($list, $pk, $pid, $child, $sorData[$pk]);
                    $arr[] = $sorData;
                }
            }
            return $arr;
        }
        return [];
    }

    /**
     * @param array $tree
     * @param string $child
     * @param string $order
     * @param array $list
     * @return array
     */
    public function treeToList(array $tree, string $child = '_child', string $order = 'id', array &$list = []): array
    {
        if (!empty($tree)) {
            foreach ($tree as $value) {
                $refer = $value;
                if (isset($refer[$child])) {
                    unset($refer[$child]);
                    $this->treeToList($value[$child], $child, $order, $list);
                }
                $list[] = $refer;
            }
            return $this->listSortBy($list, $order);
        }
        return [];
    }

    /**
     * @param array $list
     * @param string $field
     * @param string $sort
     * @return array
     */
    public function listSortBy(array $list, string $field, string $sort = 'asc'): array
    {
        if (!empty($list)) {
            $refer = $resultSet = [];
            foreach ($list as $i => $data) {
                $refer[$i] = &$data[$field];
            }
            if ($sort === 'asc') {
                // 正向排序
                asort($refer);
            } elseif ($sort === 'desc') {
                // 逆向排序
                arsort($refer);
            } elseif ($sort === 'nat') {
                natcasesort($refer);
            }
            foreach ($refer as $key => $val) {
                $resultSet[] = &$list[$key];
            }
            return $resultSet;
        }
        return [];
    }
}
